//
//  CalculateViewController.m
//  Rong360
//
//  Created by tianliwei on 6/2/14.
//  Copyright (c) 2014 tianliwei. All rights reserved.
//

#import "LoanCalculatorViewController.h"
#import "LoanResultViewController.h"
#import "LoanHistoryViewController.h"
#import "LoanCalCell.h"
#import "LoanCalculator.h"

static NSString *const CellIdentifier = @"Cell";

@interface LoanCalculatorViewController ()
@property (nonatomic, strong) CalculatePanelView *calculateView;
@property (nonatomic, strong) UIButton *hsPrevBtn;
@property (nonatomic, strong) NSArray *hsDataSource;
@property (nonatomic, strong) NSArray *titles;
@property (nonatomic, strong) NSArray *subTitles;
@property (nonatomic, strong) UITextField *currentField;
@property (nonatomic, strong) LoanCalculator *loanCal;
@property (nonatomic, assign) BOOL bBegin;
@end

@implementation LoanCalculatorViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.loanCal = [[LoanCalculator alloc]init];
    self.title = @"房贷计算器";
    self.titles = @[@"商贷金额",@"公积金金额",@"贷款期限",@"商贷利率",@"公积金利率"];
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH,(UI_NAVIFRAME_HEIGHT - CalculatorViewH - HorizonScrollH))];
    self.tableView.rowHeight = (UI_NAVIFRAME_HEIGHT - CalculatorViewH - HorizonScrollH)/self.titles.count;
    self.tableView.scrollEnabled = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"LoanCalCell" bundle:nil] forCellReuseIdentifier:CellIdentifier];
    
    [self.view addSubview:self.tableView];
    self.subTitles = @[@"万",@"万",@"年",@"%",@"%"];
    self.hsDataSource = @[@"基准利率",@"83折",@"85折",@"88折",@"9折",@"95折",@"1.1倍",@"1.2倍"];
    self.horizontalScroller = [[HorizontalScroller alloc]initWithFrame:CGRectMake(0, UI_NAVIFRAME_HEIGHT - 220, UI_SCREEN_WIDTH, HorizonScrollH)];
    self.horizontalScroller.hsDelegate = self;
    [self.horizontalScroller setButtonData:self.hsDataSource buttonGap:0 buttonWidth:70 buttonHeight:40 maskWidth:60];
    self.horizontalScroller.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    self.horizontalScroller.layer.borderWidth = .5;
    self.horizontalScroller.hidden = YES;
    [self.view addSubview:self.horizontalScroller];

    self.calculateView = [[[NSBundle mainBundle]loadNibNamed:@"CalculatePanelView" owner:self options:NULL]lastObject];
    self.calculateView.delegate = self;
    self.calculateView.Y = UI_NAVIFRAME_HEIGHT - 180;
    
    [self.view addSubview:self.calculateView];
    
    UIButton *historyButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [historyButton setBackgroundColor:[UIColor clearColor]];
    [historyButton setTitle:@"历史" forState:UIControlStateNormal];
    [historyButton addTarget:self action:@selector(history) forControlEvents:UIControlEventTouchUpInside];
    historyButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    historyButton.frame = CGRectMake(0.0f, 0.0f, 40.0f, 25.0f);
    UIBarButtonItem *historyButtonItem = [[UIBarButtonItem alloc] initWithCustomView:historyButton];
    self.navigationItem.rightBarButtonItem = historyButtonItem;
    
}

- (void)history{
    self.hidesBottomBarWhenPushed = YES;
    LoanHistoryViewController *loanHistory = [[LoanHistoryViewController alloc]init];
    [self.navigationController pushViewController:loanHistory animated:YES];
}

- (void)calculate{
    switch (self.currentField.tag) {
        case 0:
            self.loanCal.bloan = self.currentField.text;
            break;
        case 1:
            self.loanCal.gloan = self.currentField.text;
            break;
        case 2:
            self.loanCal.deadline = self.currentField.text;
            break;
        case 3:
            self.loanCal.brate = self.currentField.text;
            break;
        case 4:
            self.loanCal.grate = self.currentField.text;
            break;
        default:
            break;
    }
    if (0) {//今后再写
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"对不起，请将选项填写完整" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }else{
        [self.loanCal beginCalculate];
        self.hidesBottomBarWhenPushed = YES;
        LoanResultViewController *loanResultVC = [[LoanResultViewController alloc]initWithLoanCal:self.loanCal];
        [self.navigationController pushViewController:loanResultVC animated:YES];
    }
}

- (void)keyBtnClicked:(UIButton *)sender{
    NSString *currentStr = self.currentField.text;
    switch (sender.tag) {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
        case 8:
        case 9:{
            [self inputNumber:sender.titleLabel.text];
            break;
        }
        case 10:{//"."
            BOOL notDot = ([self.currentField.text rangeOfString:@"."].location == NSNotFound);
            if(notDot){
                 currentStr= [currentStr stringByAppendingString:@"."];
                 self.currentField.text= currentStr;
            }
            break;
        }
        case 11:{//"C"
            self.currentField.text = @"";
            self.bBegin = YES;
            break;
        }
        case 12:{
            [self calculate];
            break;
        }
        default:
            break;
    }
}

- (void)inputNumber:(NSString *)str
{
    
    if([self.currentField.text isEqualToString:@"0"] && [str isEqualToString:@"0"]){
        return;
    }
    if(self.bBegin){
        self.currentField.text= str;
    }else{
        self.currentField.text= [self.currentField.text stringByAppendingString:str];
    }
    self.bBegin= NO;
}
    
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return self.titles.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LoanCalCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell.mainLabel.text = self.titles[indexPath.row];
    cell.unitLabel.text = self.subTitles[indexPath.row];
    cell.textField.delegate = self;
    cell.textField.inputView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 1, 1)];
    cell.textField.tag = indexPath.row;
    
    [cell.textField setUserInteractionEnabled:NO];//add by tian

    // Configure the cell...
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    LoanCalCell *cell = (LoanCalCell *)[tableView cellForRowAtIndexPath:indexPath];
    [cell.textField setUserInteractionEnabled:YES];//add by tian
    [cell.textField becomeFirstResponder];
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    switch (textField.tag) {
        case 0:
            self.loanCal.bloan = textField.text;
            break;
        case 1:
            self.loanCal.gloan = textField.text;
            break;
        case 2:
            self.loanCal.deadline = textField.text;
            break;
        case 3:
            self.loanCal.brate = textField.text;
            break;
        case 4:
            self.loanCal.grate = textField.text;
            break;
        default:
            break;
    }
    [textField setUserInteractionEnabled:NO];//add by tian
    return YES;
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    switch (textField.tag) {
        case 0:
        case 1:
        case 2:
            self.horizontalScroller.hidden = YES;
            break;
        case 3:
        case 4:
            self.horizontalScroller.hidden = NO;
        default:
            break;
    }
    self.currentField = textField;
    return YES;
}


#pragma HorizontalScrollerDelegate Method
- (void)horizontalScroller:(HorizontalScroller *)scroller didSelectColumnAtIndex:(NSInteger)index{
    if (self.hsPrevBtn) {
        [self.hsPrevBtn setSelected:NO];
    }
    for (UIButton *btn in scroller.subviews) {
        if (btn.tag == index) {
            [btn setSelected:YES];
            self.hsPrevBtn = btn;
        }
    }
    
    CGFloat jzll = 0;
    if (self.currentField.tag == 3) {
        jzll = [[Config shareConfig].jizhun_house floatValue];
    }else if (self.currentField.tag == 4){
        jzll = [[Config shareConfig].jizhun_gjj floatValue];
    }
    
    switch (index) {
        case 0:
            self.currentField.text = [FloatUtil stringFromFloat:jzll];
            break;
        case 1:
            self.currentField.text = [FloatUtil stringFromFloat:jzll * 0.83];
            break;
        case 2:
            self.currentField.text = [FloatUtil stringFromFloat:jzll * 0.85];
            break;
        case 3:
            self.currentField.text = [FloatUtil stringFromFloat:jzll * 0.88];
            break;
        case 4:
            self.currentField.text = [FloatUtil stringFromFloat:jzll * 0.90];
            break;
        case 5:
            self.currentField.text = [FloatUtil stringFromFloat:jzll * 0.95];
            break;
        case 6:
            self.currentField.text = [FloatUtil stringFromFloat:jzll * 1.1];
            break;
        case 7:
            self.currentField.text = [FloatUtil stringFromFloat:jzll * 1.2];
            break;
        default:
            break;
    }
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
